<?php

define("_ROOT_PATH", realpath(dirname(__FILE__)) . '/');

//define host name

//manual define host without www
#define('_HOST_NAME', 'example.host');

if (!defined('_HOST_NAME'))
{
	$hostName = $_SERVER['HTTP_HOST'] ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
	if (0 === strpos($hostName, 'www.'))
	{
		$hostName = substr($hostName, 4);
	}

	define('_HOST_NAME', $hostName);
}

$pathToSite = str_replace('\\', '/', _ROOT_PATH);
if ($_SERVER['DOCUMENT_ROOT'] && (strpos($pathToSite, $_SERVER['DOCUMENT_ROOT']) === 0))
{
	define("_ROOT_URL", substr($pathToSite, strlen($_SERVER['DOCUMENT_ROOT'])));
}
else
{
	define("_ROOT_URL", '/');
}

//static domain settings
define('_ROOT_URL_STATIC', /*_ROOT_URL*/'http://static.roach.local/');

define("_DATA_PATH", _ROOT_PATH . 'data/');
define("_CORE_PATH", _DATA_PATH . 'Mozg/');
define("_APP_PATH", _DATA_PATH . 'App/');

define('_CACHE_PATH', _ROOT_PATH . '_cache/');
define('_CACHE_CONFIG_PATH', _CACHE_PATH . '_config/');
define('_CACHE_FOLDER', '_cache/');

define('_CACHE_FOLDER_STATIC', 'static/stcache/');
define('_CACHE_PATH_STATIC', _ROOT_PATH._CACHE_FOLDER_STATIC);

define('_CACHE_FOLDER_STYLE', _CACHE_FOLDER_STATIC. 'style/');
define('_CACHE_PATH_STYLE', _CACHE_PATH_STATIC. 'style/');

define('_CACHE_PATH_TMP', _CACHE_PATH. '_templates/');

define('_CACHE_FOLDER_THUMB', _CACHE_FOLDER_STATIC. 'images/');

define("_FILES_DIR", 'static/files/');
define("_FILES_PATH", _ROOT_PATH._FILES_DIR);

define("_EDITOR_DIR", "static/programs/ckeditor/");
define("_EDITOR_PATH", _ROOT_PATH._EDITOR_DIR);
define("_EDITOR_URL", _ROOT_URL._EDITOR_DIR);

define("_CHMOD_DIR", 0777);
define("_CHMOD_FILE", 0666);

define("_FILEMANAGER_DIR", 'static/programs/filemanager/');
define("_FILEMANAGER_PATH", _ROOT_PATH._FILEMANAGER_DIR);
define("_FILEMANAGER_URL", _ROOT_URL._FILEMANAGER_DIR);


/*------autoloader-----*/
class MozgAutoload
{
	protected static $_cacheLoader = false;

	protected static $_loadCachedClasses = false;

	protected static $_getStat = false;
	protected static $_cacheMinPercent = 70;

	protected static $_classStat = array();
	protected static $_totalRequests = 0;

	public static function register()
	{
		self::LoadCachedClasses();

		if (!spl_autoload_register('MozgAutoload::load'))
		{
			throw new Exception('Could not register class autoload function');
		}

		self::LoadStat();
	}

	protected static function LoadStat()
	{
		if (!self::$_cacheLoader) return;

		$path = self::GetStatPath();

		if (Mozg_Storage::Exists($path))
		{
			$fullsStat = Mozg_Storage::Read($path);
		}
		else
		{
			$fullStat = array('total' => 0, 'classes' => array());
		}

		self::$_totalRequests = $fullsStat['total'] + 1;
		self::$_classStat = $fullsStat['classes'];

		register_shutdown_function(array('MozgAutoload', 'SaveStat'));
	}

	public static function SaveStat()
	{
		if (!self::$_cacheLoader || !self::$_getStat) return;

		$fullStat = array('total' => self::$_totalRequests, 'classes' => self::$_classStat);
		Mozg_Storage::Save(self::GetStatPath(), $fullStat);
	}

	protected static function GetStatPath()
	{
		return _CACHE_PATH. '_classes/statistics';
	}

	protected static function LoadCachedClasses()
	{
		if (!self::$_loadCachedClasses) return;

		$path = self::GetCachePath();

		if (is_file($path))
		{
			include_once($path);
		}
	}

	protected static function GetCachePath()
	{
		return _CACHE_PATH. '_classes/classes.php';
	}

	public static function unregister()
	{
		if (!spl_autoload_unregister('MozgAutoload::load'))
		{
			throw new Exception('Could not unregister class autoload function');
		}
	}

	public static function load($className)
	{
		$classPath = _DATA_PATH.self::getFileByClass($className);
		if (!is_file($classPath)) return false;
		//echo $className. '<br>';
		include($classPath);

		if (self::$_cacheLoader) self::HandleCache($className);
	}

	public static function getFileByClass($class)
	{
		return str_replace(' ', '/', ucwords(str_replace('_', ' ', $class))).'.php';
	}

	protected static function HandleCache($className)
	{
		if (self::$_getStat)
		{
			self::GatherStat($className);
		}
		else
		{
			self::CacheClass($className);
		}
	}

	protected static function GatherStat($className)
	{
		if (!isset(self::$_classStat[$className])) self::$_classStat[$className] = 0;
		self::$_classStat[$className]++;
	}

	protected static function CacheClass($className)
	{
		if (!self::$_loadCachedClasses || !self::$_totalRequests || !isset(self::$_classStat[$className])) return;

		$classRequests = (int)self::$_classStat[$className];
		$reqPercent = $classRequests / self::$_totalRequests * 100;

		if ($reqPercent >= self::$_cacheMinPercent)
		{
			$classPath = _DATA_PATH.self::getFileByClass($className);
			$cachePath = self::GetCachePath();

			$classContent = trim(file_get_contents($classPath), ' ?>'). '?>';

			$f = fopen($cachePath, 'at');
			fwrite($f, $classContent);
			fclose($f);
		}
	}

}

//spl_autoload_extensions(".php"); // comma-separated list
MozgAutoload::register();